<template>
  <div>
    <x-header>
      {{vo.name}}
      <router-link to="/" slot="right">
        <a class="fa fa-home fa-15x"></a>
      </router-link>
    </x-header>
    <div>
      <ab-scroller ref="abScroller" 
        :url="vo.listUrl"
        :conditions="conditions"
        :custSql="true"
        :scrollObj="scrollObj"
        :listCallback="listCallback"
        v-if="vo.isInit"
        :pageSize="vo.pageSize"
        :scrollX="app.temp==4"
      >
        <div slot-scope="slotScope" :class="{ib:app.temp==4}" >
          <cell
            v-if="app.temp==1"
            v-for="(item,index) in slotScope.rows"
            :key="index"
            :title="getVal(item,app.titleKey)"
            :value="getVal(item,app.valueKey)"
            :inline-desc="getVal(item,app.descKey)"
          >
            <div>
              <span
                class="weui-btn weui-btn_mini weui-btn_plain-primary ml2"
                v-for="(btn,index1) in buttonList"
                :key="btn.alias"
                v-if="btn.type!=2"
                v-show="excuExp(item,btn.exp)"
                v-on:click="buttonClick(btn,item)"
              >{{btn.name}}</span>
            </div>
          </cell>
          <div v-if="app.temp==2 || app.temp==3">
            <div
              v-for="(item,index6) in slotScope.rows"
              :key="index6"
              class="pl20 pt5 pb5"
              style="border-bottom: 1px dotted #c7c7c7;"
            >
              <div
                v-for="(f,index1) in fields"
                :key="index1"
                v-if="f.hidden==0"
                class="ib"
                :class="{w100:app.temp==2,w50:app.temp==3}"
              >
                <span class="fb">{{f.fieldDesc}}:</span>
                <span class="pl10">{{item[f.fieldName]}}</span>
              </div>
              <br />
              <span
                class="weui-btn weui-btn_mini weui-btn_plain-primary ml2"
                v-for="(btn,index99) in buttonList" :key="btn.alias"
                v-if="btn.type!=2"
                v-show="excuExp(item,btn.exp)"
                v-on:click="buttonClick(btn,item)"
              >{{btn.name}}</span>
            </div>
          </div>
          <div v-if="app.temp==4&&slotScope.rows.length>0" class="ib">
            <table class="table table-bordered text-center">
              <thead>
                <tr>
                  <th class="th-nowap">序号</th>
                  <th
                    class="pointer-th th-nowap"
                    v-for="(f,index) in fields"
                    :key="index"
                    v-if="f.hidden==0"
                  >{{f.fieldDesc}}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item,index) in slotScope.rows" :key="index">
                  <td>{{index+1}}</td>
                  <td class="th-nowap" v-for="(f,i) in fields" :key="i" v-if="f.hidden==0">{{item[f.fieldName]}}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </ab-scroller>
      <tabbar style="position:fixed">
        <tabbar-item v-for="(btn,index) in buttonList" :key="btn.alias" v-if="btn.type==2 && btn.clickType!='6'" v-show="excuExp({},btn.exp)">
          <span
            slot="icon"
            class="icon-success-fa fa"
            :class="btn.icon"
            v-on:click="buttonClick(btn)"
          ></span>
          <span slot="label" v-on:click="buttonClick(btn)">{{btn.name}}</span>
        </tabbar-item>
      </tabbar>
    </div>
  </div>
</template>

<script>
/**
 * 自定义列表
 */
import Vue from "vue";

export default {
  name: "formCustSqlView",
  props: [],
  data() {
    return {
      onsave: false,
      loaded: false,
      isTree: false,
      treeScope: {},
      scrollObj: {},
      vo: {},
      fields: [],
      conditions: [],
      buttonList: [],
      expand: {},
      app: {},
      pageParams: {},
      backRouter: "",
    };
  },
  created: function () {
    this.init();
  },
  methods: {
    init() {
      let code = this.$route.query.code;
      let url = this.__ctx + "/form/formCustSql/view/vo_" + code;
      let $scope = this;
      this.baseService.postForm(url, {}).then((data) => {
        if (!data.isOk) {
        	Vue.tools.alert(data.msg,"错误信息");
          return;
        }

        $scope.vo = data.data;

        $scope.vo.isInit = true;

        // 字段列表
        $scope.fields = data.data.fieldsList;

        // 查询列表
        $scope.conditions = ps(data.data.conditions) || [];
        // 按钮列表
        $scope.buttonList = ps(data.data.buttons) || [];
        // 扩展参数
        $scope.expand = ps(data.data.expand) || {};
        // app属性
        $scope.app = $scope.expand.app;

        // 数据查询地址
        $scope.vo.listUrl = this.__ctx + "/form/formCustSql/view/list_" + code;
        // sql调试地址
        $scope.vo.sqlUrl = this.__ctx + "/form/formCustSql/view/sql_" + code;
        // 数据导出地址
        $scope.vo.exportUrl =
          this.__ctx + "/form/formCustSql/view/export_" + code;
        // 数据导入地址
        $scope.vo.importUrl =
          this.__ctx + "/form/formCustSql/view/import_" + code;

        // 按钮页面
        $scope.searchBtnToolsHtml =
          "../../../form/formCustSql/view/search-tool-page.html";

        // 按钮权限编码
        $scope.vo.exportOperAlias = "customsql_export_" + code;

        // 页面参数
        $scope.pageParams = {};

        var params = this.$route.query["initParam"];

        params = ps(params) || {};

        params = Object.assign(params, this.$route.query);

        // 删掉自定义列表的code参数
        delete params.code;
        if (params) {
          if (typeof param == "string") {
            $scope.pageParams.params = params;
          } else {
            $scope.pageParams.params = JSON.stringify(params);
          }
        }

        var treeSetting = $scope.expand.tree;
        if (treeSetting && treeSetting.showTree == 1) {
          $scope.isTree = true;
        }

        // 初始化参数
        $scope.vo.initParam = Object.assign({}, params);
        window.initParam = $scope.vo.initParam;

        this.initSearch();

        // 如果是table布局,则设置下面的参数,否则无法横向滚动
        if (this.app.temp == 4) {
          window.setTimeout(function () {
            $("._v-content").css({
              width: "initial",
              display: "inline-block",
            });
            $("._v-container").css({
              width: "initial",
            });
          }, 1000);
        }
      });
    },
    initSearch: function () {
      let $scope = this;
      var conditions = [];
      for (var i = 0; i < $scope.conditions.length; i++) {
        var con = $scope.conditions[i];
        
        var json = null;
        // 需要格式化的 下拉框,复选框,单选框,json
        if([10,14,4,6,8].indexOf(con.ctltype)!=-1 && con.json){
        	con.json = ps(con.json);
        }
        // 数据字典
        if([5,7].indexOf(con.ctltype)!=-1 && con.json){
        	con.json = this.vo.dicMap[con.json];
        }
        
        var cnType = con.cntype;
        var betweenCondition = false;
        if (cnType.indexOf(",") > 0) {
			cnType = cnType.split(",");
			betweenCondition = {cntype:cnType[1]};
			cnType = cnType[0];
		}
        
        
        //   if(con.app == 1){
        conditions.push({
          name: con.name,
          desc: con.desc,
          val: con.val,
          json: con.json || con.json,
          paramType: con.paramType,
          ctltype: con.ctltype,
          cntype:cnType,
          betweenCondition : betweenCondition
        });
        //   }
      }
      this.conditions = conditions;
    },
    listCallback: function (data, scope) {
      scope = scope || this;

      var list = data.list;
      // 如果没有数据,则返回
      if (!list || list.length == 0) {
        return;
      }
      var fields = scope.fields;
      for (var j = 0; j < fields.length; j++) {
        fields[j].tdData = [];
      }
      for (var j = 0; j < fields.length; j++) {
        for (var i = 0; i < list.length; i++) {
          var dataJson = scope.getTdata({
            tempItem: list[i],
            field: fields[j],
            type: "sql",
            pindex: i,
            index: j,
            scope: scope,
          });
          fields[j].tdData.push(dataJson.t); // 将转换后的值存入这里
          if (dataJson.bindHtml) {
            fields[j].bindHtml = true;
          }

          list[i][fields[j].fieldName] = dataJson.t;
        }
      }
    },
    /*** 获取格式化后的列表数据*/
    getTdata: function (options) {
      var tempItem = options.tempItem;
      var field = options.field;
      var type = options.type;
      var pindex = options.pindex;
      var index = options.index;
      var scope = options.scope;

      if (!tempItem) return;

      var lowFieldName = field.fieldName;
      var item = tempItem;
      var val = getValByScope({
        scope: item,
        exp: lowFieldName,
      });

      // 单位替换
      if (field.unit) {
        val = eval("(function(){" + field.unit + "})()");
        return {
          o: val, // 原始值
          t: val, // 转换后的值
        };
      }

      if (!val && val !== 0) {
        return {
          o: val, // 原始值
          t: val, // 转换后的值
        };
      }

      if (
        field.dataType == "date" ||
        field.dataType == "datetime" ||
        field.dataType == "timestamp"
      ) {
        if (field.dateFormat && val) {
          if (val.time) {
            return {
              o: new Date(val.time).format(field.dateFormat), // 原始值
              t: new Date(val.time).format(field.dateFormat), // 转换后的值
            };
          }
          if (typeof val == "number") {
            return {
              o: val, // 原始值
              t: new Date(val).format(field.dateFormat), // 转换后的值
            };
          }
          return {
            o: val, // 原始值
            t: new Date((val + "").replaceAll("-", "/")).format(
              field.dateFormat
            ), // 转换后的值
          };
        }
      }

      return this.getData({
        field: field,
        val: val,
        scope: scope,
        tempItem: tempItem,
      });
    },
    getData: function (options) {
      var field = options.field;
      var val = options.val;
      var scope = options.scope;
      var tempItem = options.tempItem;
      switch (field.controlType) {
        case 1: // 单行文本
          return {
            o: val, // 原始值
            t: val, // 转换后的值
          };
        case 4: // 下拉框
        case 6: // 单选框
          // case 8 :// 下拉框多选
          field.dateFormat = ps(field.dateFormat);
          if (field.dateFormat && field.dateFormat[val]) {
            return {
              o: val, // 原始值
              t: field.dateFormat[val], // 转换后的值
            };
          }
          return {
            o: val, // 原始值
            t: val, // 转换后的值
          };
        case 5: // 下拉框字典
        case 7: // [字典]单选框
          if (field.dateFormat) {
            var rtObj = {
              o: val,
              t: val,
            };
            rtObj.t = scope.vo.dicMap[field.dateFormat][val];
            return rtObj;
          }
          return {
            o: val, // 原始值
            t: val,
            // 转换后的值
          };
        case 8: // 复选框
          field.dateFormat = ps(field.dateFormat);
          if (field.dateFormat && !isStrNull(val)) {
            var tempVal = "";
            if (typeof val == "string") {
              val = val.split(",");
            }
            for (var i = 0; i < val.length; i++) {
              tempVal = tempVal + (field.dateFormat[val[i]] || val[i]) + ",";
            }
            return {
              o: val, // 原始值
              t: tempVal.substring(0, tempVal.length - 1),
              // 转换后的值
            };
          }
          return {
            o: val, // 原始值
            t: val,
            // 转换后的值
          };
        case 9: // 复选框 字典
          if (field.dateFormat && !isStrNull(val)) {
            var rtObj = {
              o: val,
              t: val,
            };

            var json = scope.vo.dicMap[field.dateFormat];
            var tempVal = "";
            val = val.split(",");
            for (var i = 0; i < val.length; i++) {
              tempVal = tempVal + (json[val[i]] || val[i]) + ",";
            }
            rtObj.t = tempVal.substring(0, tempVal.length - 1);

            return rtObj;
          }
          return val;
        case 3: // 日期类型
          if (field.dateFormat) {
            return {
              o: val, // 原始值
              t: new Date(val).format(field.dateFormat),
              // 转换后的值
            };
          }
          return {
            o: val, // 原始值
            t: val, // 转换后的值
          };
        case 10: // JSON
          return {
            o: val, // 原始值
            t: getDataByKey(val, field.dateFormat), // 转换后的值
          };
          break;
        default:
          return {
            o: val, // 原始值
            t: val,
            // 转换后的值
          };
      }
    },
    getVal: function (data, key) {
      return data[key];
    },
    btnTiggerFn: function (btn, item) {
      let scope = this;
      var url = this.replaceUrl(btn.url, item);
      var code = this.vo.code;
      var expand = ps(btn.expand) || {};
      var hrefSetting = expand.hrefSetting || {};
      var clickType = hrefSetting.openType || btn.clickType;
      var width = hrefSetting.width || "100";
      var height = hrefSetting.height || "100";
      var widthUnit = hrefSetting.widthUnit == "px" ? "" : "%";
      var heightUnit = hrefSetting.heightUnit == "px" ? "" : "%";
      if (url.indexOf("form/formDef/vueFormDefPreview.html") >= 0) {
        url = url.replaceAll(
          "form/formDef/vueFormDefPreview.html",
          "bpm/preview"
        );
      } else if (url.indexOf("form/formDef/vueFormDetail.html") >= 0) {
        url = url.replaceAll(
          "form/formDef/vueFormDetail.html\\?",
          "bpm/preview?isReadOnly=1&"
        );
      } else if (url.indexOf("form/formDefData/removeData/") >= 0) {
        var appKey = this.getParam('appKey',url);
        if(appKey){
          var list = url.split("/");
          list[4]=appKey;
          url = list.join("/");
        }
      }

      switch (clickType) {
        case "0": // 直接请求
          if (!url) {
            this.$vux.alert.show("url地址为空~");
            return;
          }
          this.postUrl(url, {}, btn);
          break;
        case "1": // 事件按钮
          url = "/form/formCustSql/view/changeData_" + code + "_" + btn.alias;
          if (item) {
            this.postUrl(
              url,
              {
                id: item[hrefSetting.dataChangeRelField || parent.vo.pkName],
              },
              btn
            );
          } else {
            // 全局按钮
            var ids = "";
            this.postUrl(
              url,
              {
                id: ids,
              },
              btn
            );
          }

          break;
        case "3": // 对话框
        case "4": // 对话框
          // 因为APP是单页面的 对话框的方式不友好,所以选择用标签页
          if (url && !url.startWith("/")) {
            url = "/" + url;
          }
          scope.$router.push({ path: url });
          break;
      }
    },
    postUrl: function (url, params, btn) {
      var scope = this;
      params = params || {};
      if (!url.startWith("http")) {
        url = this.__ctx + url;
      }
      scope.baseService.post(url, params).then(function (data) {
        if (data.isOk) {
          scope.$vux.alert.show(btn.successTxt || "操作成功~");
          scope.$refs.abScroller.find();
        } else {
          scope.$vux.alert.show(data.msg);
        }
      });
    },
    replaceUrl: function (url, param) {
      var scope = this;
      if (!url) {
        return "";
      }
      if (!param) {
        // 没有参数则表示是全局按钮
        param = {};
      }

      // 获取URL中的变量
      var urlParams = scope.$route.query;
      param = Object.assign(param, urlParams);

      var hrefnew = url;
      // 替换${}
      var p1 = /\#\{(\w+)\}/g;
      try {
        var vars = hrefnew.match(p1);
        for (var i = 0; i < vars.length; i++) {
          var keyt = vars[i];
          var p2 = /\#\{(\w+)\}/g;
          var key = p2.exec(keyt);
          hrefnew = hrefnew.replace(keyt, param[key[1]]);
        }
      } catch (ex) {}
      // 替换#{}
      p1 = /\$\{(\w+)\}/g;
      try {
        var vars = hrefnew.match(p1);
        for (var i = 0; i < vars.length; i++) {
          var keyt = vars[i];
          var p2 = /\$\{(\w+)\}/g;
          var key = p2.exec(keyt);
          hrefnew = hrefnew.replace(keyt, param[key[1]]);
        }
      } catch (ex) {}
      // 替换{}
      p1 = /\{(\w+)\}/g;
      try {
        var vars = hrefnew.match(p1);
        for (var i = 0; i < vars.length; i++) {
          var keyt = vars[i];
          var p2 = /\{(\w+)\}/g;
          var key = p2.exec(keyt);
          hrefnew = hrefnew.replace(keyt, param[key[1]]);
        }
      } catch (ex) {}
      return hrefnew;
    },
    getParam : function(name,url){
        url = url || window.location.href;
        var locUrl = url.substr(url.indexOf("?")+1);
        var aryParams=locUrl.split("&");
        var rtn="";
        for(var i=0;i<aryParams.length;i++){
          var pair=aryParams[i];
          var aryEnt=pair.split("=");
          var key=aryEnt[0];
          var val=aryEnt[1];
          if(key!=name) continue;
          if(rtn==""){
            rtn=val;
          }
          else{
            rtn+="," + val;
          }
        }
        return rtn;
    },
    excuExp: function (item, exp, type) {
      if (isStrNull(exp)) return "";
      var data = item; // 这个变量不能删
      if (type == 1) {
        exp = "(function(){" + exp + "})()";
      }
      try {
        var returnData = eval(exp);
        if (returnData && typeof returnData == "string") {
          returnData = returnData.replaceAll("undefined", "");
        }
        return returnData;
      } catch (e) {
        return "";
      }
    },
    buttonClick: function (btn, data) {
      let scope = this;
      if (btn.warnTxt) {
        this.$vux.confirm.show({
          content: btn.warnTxt,
          title: "温馨提示",
          // 组件除show外的属性
          onCancel() {},
          onConfirm() {
            scope.btnTiggerFn(btn, data);
          },
        });
      } else {
        scope.btnTiggerFn(btn, data);
      }
    },
  },
};
</script>
